package com.aruba.paging4.paging.boundarycallback;

import android.os.AsyncTask;

import androidx.annotation.NonNull;
import androidx.paging.PagedList;

import com.aruba.paging4.api.RetrofitClient;
import com.aruba.paging4.database.MyDataBase;
import com.aruba.paging4.entity.Movie;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by aruba on 2021/9/18.
 */
public class MovieBoundaryCallback extends PagedList.BoundaryCallback<Movie> {
    public static final int PER_PAGE = 10;

    @Override
    public void onZeroItemsLoaded() {
        super.onZeroItemsLoaded();
        //加载第一页
        getTopData();
    }

    private void getTopData() {
        RetrofitClient.getInstance().getApi()
                .getMovies(0, PER_PAGE)
                .enqueue(new Callback<List<Movie>>() {
                    @Override
                    public void onResponse(Call<List<Movie>> call, Response<List<Movie>> response) {
                        if (response.body() != null)
                            insertMovies(response.body());
                    }

                    @Override
                    public void onFailure(Call<List<Movie>> call, Throwable t) {

                    }
                });
    }

    private void insertMovies(List<Movie> body) {
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... voids) {
                MyDataBase.getInstance().getMovieDao().insertMovies(body);
                return null;
            }
        }.execute();
    }

    @Override
    public void onItemAtEndLoaded(@NonNull Movie itemAtEnd) {
        super.onItemAtEndLoaded(itemAtEnd);
        //加载第二页
        getAfterData(itemAtEnd);
    }

    private void getAfterData(Movie movie) {
        RetrofitClient.getInstance().getApi()
                .getMovies(movie.id, PER_PAGE)
                .enqueue(new Callback<List<Movie>>() {
                    @Override
                    public void onResponse(Call<List<Movie>> call, Response<List<Movie>> response) {
                        if (response.body() != null)
                            insertMovies(response.body());
                    }

                    @Override
                    public void onFailure(Call<List<Movie>> call, Throwable t) {

                    }
                });
    }
}
